package com.tan.steamship.controller;

import com.tan.steamship.common.Result;
import com.tan.steamship.domain.UserPo;
import com.tan.steamship.dto.UserDto;
import com.tan.steamship.service.UserService;
import com.tan.steamship.util.BeanUtil;
import com.tan.steamship.util.CookieUtil;
import com.tan.steamship.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: 用户信息
 * @author: longshifu
 * @time: 2024/12/10 20:55
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody UserPo user, HttpServletRequest request, HttpServletResponse response) {
        user = userService.login(user);
        // 添加cookie，设置唯一认证
        String encode = MD5Util.MD5Encode(user.getName() + user.getPassword(), "UTF-8");
        // 进行加盐
        encode += "|" + user.getId() + "|" + user.getName() + "|";
        CookieUtil.setCookie(request, response, "XM_TOKEN", encode, 1800);
        // 将encode放入redis中，用于认证
        try {
            redisTemplate.opsForHash().putAll(encode, BeanUtil.bean2map(user));
            // 设置过期时间
            redisTemplate.expire(encode, 30 * 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将密码设为null,返回给前端
        user.setPassword(null);
        return Result.success("登录成功",user);
    }

    /**
     * 用户注册
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {
        userService.register(userDto);
        return Result.success("注册成功");
    }

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody UserDto userDto) {
        userService.saveOrUpdate(userDto);
        return Result.success();
    }

    @GetMapping("/list")
    public Result listShips(@RequestParam(value = "userName", required = false) String userName,
                            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
                            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return Result.success(userService.listUser(userName,pageIndex, pageSize));
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam("id") String id) {
        return Result.success(userService.detail(id));
    }

    @GetMapping("/delete")
    public Result delete(@RequestParam("id") String id) {
        userService.removeById(id);
        return Result.success();
    }

    /**
     * 判断用户名是否已存在
     * @param username
     * @return
     */
    @GetMapping("/username/{username}")
    public Result isExist(@PathVariable String username) {
        userService.isExist(username);
        return Result.success("可注册");

    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/token")
    public Result token(@CookieValue("XM_TOKEN") String token, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map map = redisTemplate.opsForHash().entries(token);
        // 可能map为空 ， 即redis中时间已过期，但是cookie还存在。
        // 这个时候应该删除cookie，让用户重新登录
        if (map.isEmpty()) {
            CookieUtil.delCookie(request, token);
            return Result.error(1002, "账号过期,请重新登录");
        }
        // 设置过期时间
        redisTemplate.expire(token, 30 * 60, TimeUnit.SECONDS);
        UserPo user = BeanUtil.map2bean(map, UserPo.class);
        user.setPassword(null);
        return Result.success(user);
    }
}
